package com.example.lotterysystem.service.impl;

import com.example.lotterysystem.common.errorcode.ServiceErrorCodeConstants;
import com.example.lotterysystem.common.exception.ServiceException;
import com.example.lotterysystem.common.utils.*;
import com.example.lotterysystem.service.VerificationCodeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class VerificationCodeServiceImpl implements VerificationCodeService {

    @Autowired
    private SMSUtil smsUtil;
    @Autowired
    private RedisUtil redisUtil;

    private static final int CAPTCHA_CODE_LENGTH = 4;
    private static final String TEMPLATE_CODE = "SMS_476715195";
    private static final Long CAPTCHA_CODE_TIMEOUT = 5 * 60L; // 单位为 s
    private static final String CAPTCHA_CODE_REDIS_PREFIX = "captcha_code_";

    @Override
    public void sendVerificationCode(String phoneNumber) {
        // 校验手机号是否正确
        if (!StringUtils.hasText(phoneNumber) || !RegexUtil.checkMobile(phoneNumber)) {
            throw new ServiceException(ServiceErrorCodeConstants.PHONE_NUMBER_ERROR);
        }
        // 生成验证码
        String captcha = CaptchaUtil.createCaptchaCode(CAPTCHA_CODE_LENGTH);

        // 发送验证码
        Map<String, String> templateParam = new HashMap<>();
        templateParam.put("code", captcha);
        smsUtil.sendMessage(TEMPLATE_CODE, phoneNumber, JacksonUtil.writeValueAsString(templateParam));
        log.info("向用户 {} 发送验证码 {}", phoneNumber, captcha);
        // 将验证码存储到 redis 中
        redisUtil.set(CAPTCHA_CODE_REDIS_PREFIX + phoneNumber, captcha, CAPTCHA_CODE_TIMEOUT);
    }

    @Override
    public String getVerificationCode(String phoneNumber) {
        // 校验手机号是否正确
        if (!StringUtils.hasText(phoneNumber) || !RegexUtil.checkMobile(phoneNumber)) {
            throw new ServiceException(ServiceErrorCodeConstants.PHONE_NUMBER_ERROR);
        }
        // 从 redis 中获取验证码 并返回
        return redisUtil.get(CAPTCHA_CODE_REDIS_PREFIX + phoneNumber);
    }
}

